package lv.solcraft.replication.client.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;

import lv.solcraft.replication.common.server.SessionFacade;

import org.apache.log4j.Logger;
import org.restlet.Client;
import org.restlet.data.CharacterSet;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Response;
import org.restlet.resource.StringRepresentation;

public class HttpSessionFacade implements SessionFacade {

    private static Logger log = Logger.getLogger(HttpSessionFacade.class);

    private String serverUrl;

    public void setServerUrl(String serverUrl) {
        this.serverUrl = serverUrl;
    }

    public void logEvent(String server, String eventType, int siteId, String message) {
        try {
            doPost(server, eventType, siteId, message);
        } catch (Exception e) {
            log.warn("Logging request failed", e);
        }
    }

    private void doPost(String server, String eventType, int siteId, String message) throws MalformedURLException,
            IOException, ProtocolException, UnsupportedEncodingException {
        String urlString = serverUrl + "/" + server + "/log/" + siteId + "/" + eventType;
        Client client = HttpClientFactory.get();
        Response response = client.post(urlString, new StringRepresentation(message, MediaType.TEXT_PLAIN,
                Language.ALL, CharacterSet.UTF_8));
        try {
            if (!response.getStatus().isSuccess()) {
                log.warn("Logging failed with response code " + response.getStatus() + ", url " + urlString);
            }
        } finally {
            response.release();
        }
    }
}
